﻿#!usr/bin/env python3

#D:\workspace\python\flask_mz\venv\Scripts

#ctrl+u 变小写
#ctrl+shift+u 变小写

from flask import Flask,render_template,request,redirect,url_for,make_response,abort
from werkzeug.routing import BaseConverter
from werkzeug.utils import secure_filename
import os,stat
from flask_script import Manager

#自定义一个路由转换器,支持正则表达式
class RegexConverter(BaseConverter):
	def __init__(self,url_map,*items):
		super(RegexConverter, self).__init__(url_map)
		self.regex = items[0]

app = Flask(__name__)
#注册自定义的路由转换器,名称为 'regex'
app.url_map.converters['regex'] = RegexConverter
mgr = Manager(app) #启用第三方包来管理代码

@app.route("/")
def index():
	return render_template("index.html",
						   title="<h1>wellcome to kfz's site hello</h1>",
						   tips="##header2")

@app.route("/services")
def services():
	return "services"

@app.route("/about")
def about():
	return "about"

#多种路由参数的讲解,可以指定参数类型,例如(支持类型有:int ,float path):
@app.route('/user/<int:user_id>')
def get_user(user_id):
	return  'user_id is =>%s' %user_id+',wellcome!'

#测试自定义的正则表达式路由
@app.route('/uname/<regex("[a-z]{3}"):uname>')
def get_uname(uname):
	return "uname is => %s"%uname

@app.route("/login",methods=['GET','POST'])
def login():
	return render_template("login.html",method=request.method)

#上传文件的例子
@app.route("/upload",methods=["GET","POST"])
def upload():
	if request.method=="POST":
		f = request.files['file'] #key对应表单里面的名字
		basePath = os.path.abspath(os.path.dirname(__file__))
		#注意路径设置,用join设置 保证路径格式正确
		uploadPath = os.path.join(basePath,"static")
		uploadPath = os.path.join(uploadPath,"uploads")
		#os.chmod(uploadPath, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
		uploadPath = os.path.join(uploadPath,secure_filename(f.filename))
		f.save(uploadPath)
		return redirect(url_for("upload"))
	return  render_template("upload.html")

#通过livereload扩展模块实时监测项目，实现可见即可得(修改的页面可以马上见到效果，不需要重启服务器)
@mgr.command
def dev():
	from livereload import Server
	ser = Server(app.wsgi_app)
	url = os.path.join("**","*.*")
	print(url)
	ser.watch(url)
	ser.serve(open_url_delay=1)

#自定义模板过滤器，针对markdown语法
@app.template_filter("md")
def mark_down_to_html(text):
	from  markdown import markdown
	html = markdown(text)
	print(html)
	return html

def read_data(text):
	return text

#这个装饰器的作用是把函数注册到jinjia2模板中
@app.context_processor
def insert_function():
	return dict(read_data=read_data) #key名将是模板中调用的名称


if __name__=="__main__":
	app.run(debug=True)
	#mgr.run()